package org.tgit.gateway.config;

import java.util.List;
import java.util.Map;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;


import reactor.core.publisher.Mono;
/**
 *
* @ClassName: GlobalExceptionHandler   
* @Description: ( 全局异常切面，json格式做返回)  DefaultErrorWebExceptionHandler是-1 
* @author 范再军   
* @date 2018年4月17日 上午9:24:02   
*
 */
//@Component
//@Order(-2)
public class GlobalErrorWebExceptionHandlerConfig extends AbstractErrorWebExceptionHandler{
	

	public GlobalErrorWebExceptionHandlerConfig(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
			ApplicationContext applicationContext) {
		super(errorAttributes, resourceProperties, applicationContext);
	}

	@Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {

       Map<String, Object> errorPropertiesMap = getErrorAttributes(request, false);
       
       return ServerResponse.status(HttpStatus.BAD_REQUEST)
         .contentType(MediaType.APPLICATION_JSON_UTF8)
         .body(BodyInserters.fromObject(errorPropertiesMap));
    }
	 
}
